package cn.minis.beans.processor;

import cn.minis.beans.BeansException;
import cn.minis.beans.factory.AutowireCapableBeanFactory;
import cn.minis.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;

public class AutowiredAnnotationBeanPostProcessor implements BeanPostProcessor {
  
  private AutowireCapableBeanFactory beanFactory;
  
  
  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    Object result = bean;
  
    Class<?> clazz = bean.getClass();
    Field[] declaredFields = clazz.getDeclaredFields();
    if (declaredFields != null) {
      for (Field field : declaredFields) {
        boolean annotationPresent = field.isAnnotationPresent(Autowired.class);
        if (annotationPresent) {
          // 设置属性内容
          String name = field.getName();
          Object autowiredObj = this.getBeanFactory().getBean(name);
          //设置属性值，完成注入
          try {
            field.setAccessible(true);
            field.set(bean, autowiredObj);
            System.out.println("autowire " + name + " for bean " + beanName);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  
    return result;
  }
  
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return null;
  }
  
  public AutowireCapableBeanFactory getBeanFactory() {
    return beanFactory;
  }
  public void setBeanFactory(AutowireCapableBeanFactory beanFactory) {
    this.beanFactory = beanFactory;
  }
}
